package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {

        // 检验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "获取行为实体失败");
        }


        // 判断是否有过点赞行为
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);


        if (likesBehavior != null && dto.getOperation().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "您已经点过赞了，请勿重复点赞");
        }

        // 点赞
        if (dto.getOperation().intValue() == 0) {
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setType((short) 0);
            likesBehavior.setOperation((short) 0);
            likesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(likesBehavior);
        } else {
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }

        return ResponseResult.okResult();
    }
}
